import urllib
import aioredis
import aiohttp
import lxml.html
import json
import asyncio
import time
import random
from PIL import Image
import io
import logging
import sys
import os
sys.path.append(os.path.abspath('../'))
from tongji import aget_wxqrcode

logger = logging.getLogger("cmcc")


def get_uuid():
    token = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
    new_token = ""
    for i in  token:
        r = int(random.random() * 16) | 0
        if i == 'x':
            new_token += "%x" % r
        elif i == 'y':
            new_token += "%x" % (r&0x3|0x8)
        else:
            new_token += i
    return new_token

def get_ts():
    return str(time.time()).replace('.', '')[:13]

async def get_weixin_h5(tel, amount, redis, channel="wx", ip=None):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    if ip:

        headers.update({
            'CLIENT-IP': ip,
            'X-FORWARDED-FOR': ip
        })

    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    # proxy = random.choice([p for p in proxys if '@' not in p and '16817' not in p])
    proxy = random.choice([p for p in proxys if '@' not in p])
    logger.info("%s|%s", tel, proxy)
    if proxy:
        conn = proxy
    else:
        conn = None
    async with aiohttp.ClientSession(headers=headers) as session:
        url = 'https://life.10085.cn/mall/api/my?tel=%s&_=%s' % (tel, get_ts())
        async with session.get(url, proxy=conn) as rsp:
            face_data = await rsp.json()
            # logger.info(face_data)
            if face_data["code"] == '0':
                unused = await redis.sismember("unused_85_prov", face_data["data"]["province"])
                if unused:
                    logger.info("%s交费不可用", face_data["data"]["province"])
                    return None
                hf = face_data["data"]['goods']['data']['hf']
                for hf_info in hf:
                    if int(amount) == float(hf_info['showPrice']):
                        hf_id = hf_info['id']
                        break
        # 10086 下单
        is_check = await redis.get("is_check_86", encoding='utf-8')
        if is_check == '1':
            res = await aget_wxqrcode(tel, amount, redis)
            if res["retCode"] != "000000":
                logger.info("%s不可交费", tel)
                return None
        url = 'https://life.10085.cn/mall/api/rechr'
        data = {
            "gid": hf_id,
            'tel': tel,
            '_': get_ts()
        }
        async with session.get(url, params=data, proxy=conn) as rsp:
            data = await rsp.json()
            logger.info(data)
            pay_url = data['data']['pay']['url']
            querys = urllib.parse.urlparse(pay_url).query
            params = dict(urllib.parse.parse_qsl(querys))
            transId = json.loads(params["transdata"])["transid"]
            logger.info(pay_url)
        async with session.get(pay_url, proxy=conn) as rsp:
            refer_url = str(rsp.url)
            logger.info(rsp.url)
        if channel == 'ali':
            channel_code = '100108'
        elif channel == 'wxqrcode':
            channel_code = '100208'
        else:
            channel_code = '100203'
        data = {
            'payChannelCode': channel_code,
            'transId': transId,
            'token': get_uuid()
        }

        url = 'https://pay.10085.cn/zypayh5/beg?' + urllib.parse.urlencode(data)
        return url, transId, face_data["data"]["province"]
        # headers["Referer"] = refer_url
        # headers["Host"] = "pay.10085.cn"
        # async with session.get(url, params=data, headers=headers) as rsp:
        #     text = await rsp.text()
        #     print(rsp.url)
        #     print(text)

async def cmcc_query(order_id, tel, redis):

    url = 'https://pay.10085.cn/zypayh5/front/sh/opencashier!getOrderInfoByAcid'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    proxy = random.choice(list(proxys))
    logger.info(proxy)
    if proxy:
        conn = proxy
    else:
        conn = None

    data = {"uid": "u0001",
            "transid": order_id}
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.post(url, data=data, proxy=conn) as rsp:
            text = await rsp.text()
            order_info = json.loads(text)
            pay_state = order_info["bean"]["payState"]
            # if pay_state == "1":
            #     orderstate = "8"
            # elif pay_state == '2':
            #     orderstate = '0'
            # else:
            #     orderstate = '9'

            message = order_info['bean'].get('cpOrderNo')

            # return orderstate,  message
        url = 'https://life.10085.cn/mall/rechr/detail?id=%s&tel=%s' % (message, tel[-4:])
        async with session.get(url, proxy=conn) as rsp:
            text = await rsp.text()
            root = lxml.html.fromstring(text)
            ele = root.xpath('//*[@id="show-rechr-result"]')
            if ele:
                if ele[0].attrib["data-v"] == "21":
                    orderstate = "0"
                elif ele[0].attrib["data-v"] == "-1":
                    orderstate = '8'
                elif ele[0].attrib["data-v"] == "20":
                    orderstate = '1'
                else:
                    orderstate = '9'
                return orderstate, message



if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    now = time.time()
    redis = loop.run_until_complete(
        aioredis.create_redis(address=('localhost', 6379), db=0, loop=loop)
    )
    task = asyncio.ensure_future(get_weixin_h5("13418071372", "10", redis, 'ali'))
    # task = asyncio.ensure_future(cmcc_query("322018111618325377201158463", "13871137387", redis))
    loop.run_until_complete(task)
    print(time.time() - now)
    loop.close()
